package top.canyue.word_range_service.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.canyue.word_range.exception.DataIsNullException;
import top.canyue.word_range.pojo.dto.LoginUser;
import top.canyue.word_range.pojo.dto.PageDTO;
import top.canyue.word_range.pojo.dto.UserDto;
import top.canyue.word_range.pojo.po.User;
import top.canyue.word_range.pojo.query.UserQuery;
import top.canyue.word_range.pojo.vo.UserVo;
import top.canyue.word_range.result.Result;
import top.canyue.word_range.utils.PojoUtil;
import top.canyue.word_range_service.mapper.UserMapper;
import top.canyue.word_range_service.service.UserService;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    final UserMapper userMapper;
    final PasswordEncoder passwordEncoder;

    @Override
    public Result<UserVo> getUserById(String id) {
        UserVo userVo = userMapper.selectById(id).toVo();
        return Result.success(userVo);
    }

    @Override
    public PageDTO<UserVo> getUsersPage(UserQuery userQuery) {
        // 构建复杂查询条件
        String name = userQuery.getName() == null ? "" : userQuery.getName();
        String phone = userQuery.getPhone() == null ? "" : userQuery.getPhone();
        Page<User> page = userQuery.toMpPageDefaultSortOrderByRegisterDateASC();  // TODO: 后面更新

        Page<User> userPage = lambdaQuery()
                .like(!Objects.equals(name, ""),User::getName, name)
                .eq(!Objects.equals(phone, ""),User::getPhone, phone)
                .page(page);
        return PageDTO.of(userPage, UserVo.class);
    }

    @Override
    public Result<Object> resetPassword(String jwt,String newPassword) {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String loginUserId = loginUser.getUser().getId();
        String passwordHash = passwordEncoder.encode(newPassword);
        User user = new User();
        user.setId(loginUserId);
        user.setPasswordHash(passwordHash);
        boolean ok = userMapper.updateById(user) == 1;  // 正常来说就一条
        if(ok){
            return Result.success();
        }
        return Result.error("更新失败");
    }

    @Override
    public Result<UserVo> updateUserById(String id, UserDto userDto) {
        String password = userDto.getPassword();
        // 有没有一种可能，空字符串
        User user = BeanUtil.copyProperties(userDto, User.class, PojoUtil.getNullPropertyNames(userDto));
        user.setId(id);
        if(password != null && !password.isEmpty()){
            user.setPasswordHash(passwordEncoder.encode(password));
        }
        boolean ok = userMapper.updateById(user) == 1;
        if(ok){
            return getUserById(id);
        }
        return Result.error("用户信息修改失败");
    }

    @Override
    public Result<Object> deleteUserById(String id) {
        boolean ok = userMapper.deleteById(id) > 0;
        if (ok){
            return Result.success();
        }
        return Result.error("删除用户失败,请检查ID是否正确");
    }

    @Override
    public Result<Long> getRegisterDays(String jwt) {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if(loginUser != null){
            User user = loginUser.getUser();

            Date currentDate = new Date();
            // 计算时间差（毫秒）
            long diffInMillies = Math.abs(currentDate.getTime() - user.getRegisterDate().getTime());
            // 将毫秒转换为天数
            long diffInDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
            return Result.success(diffInDays);
        }
        throw new DataIsNullException();
    }

    @Override
    public Result<UserVo> updateUserByJwt(String jwt, UserDto userDto) {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if(loginUser != null){
            String userId = loginUser.getUser().getId();
            return updateUserById(userId,userDto);
        }
        throw new DataIsNullException();
    }

    @Override
    public Result<Object> deleteUserByJwt() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if(loginUser != null){
            String userId = loginUser.getUser().getId();
            return deleteUserById(userId);
        }
        throw new DataIsNullException();
    }

    @Override
    public Result<Integer> getActivityIntegral() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if(loginUser != null){
            User user = loginUser.getUser();
            User userData = userMapper.selectById(user.getId());
            return Result.success(userData.getActivityIntegral());
        }
        throw new DataIsNullException();
    }

}
